package com.che.libcommon.utils;

import io.reactivex.Flowable;
import io.reactivex.FlowableTransformer;
import io.reactivex.Maybe;
import io.reactivex.MaybeSource;
import io.reactivex.MaybeTransformer;
import io.reactivex.Observable;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.SingleSource;
import io.reactivex.SingleTransformer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import org.reactivestreams.Publisher;

public class RxHelper {

  //方便切换线程
  //.compose(RxHelper.io2main())
  public static <T> SchedulerTransformer<T, T> io2main() {
    return new SchedulerTransformer<T, T>() {
      @Override
      public MaybeSource<T> apply(Maybe<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
      }

      @Override
      public SingleSource<T> apply(Single<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
      }

      @Override
      public ObservableSource<T> apply(Observable<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
      }

      @Override
      public Publisher<T> apply(Flowable<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread());
      }
    };
  }


  public static <T> SchedulerTransformer<T, T> switch2io() {
    return new SchedulerTransformer<T, T>() {
      @Override
      public MaybeSource<T> apply(Maybe<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io());
      }

      @Override
      public SingleSource<T> apply(Single<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io());
      }

      @Override
      public ObservableSource<T> apply(Observable<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io());
      }

      @Override
      public Publisher<T> apply(Flowable<T> upstream) {
        return upstream.subscribeOn(Schedulers.io())
            .observeOn(Schedulers.io());
      }
    };
  }

  interface SchedulerTransformer<Upstream, Downstream> extends
      FlowableTransformer<Upstream, Downstream>,ObservableTransformer<Upstream, Downstream>,SingleTransformer<Upstream, Downstream>,
      MaybeTransformer<Upstream, Downstream> {

  }

}
